import { t } from 'i18next'
import createVanilla from 'zustand/vanilla'
import create from 'zustand'
import { subscribeWithSelector } from 'zustand/middleware'
import { fetchApprovalConfs, fetchAuditOPT } from '@/api/auditManager'
import Alert from '@/components/Alert'
import { FetchMeetingListItem } from '@/api/auditManager/interface'
import { Message } from '@kedacom/react-next'

interface ManagerStore {
	// 申请互动弹窗权限队列
	meetingList: Array<FetchMeetingListItem>
	// 驳回弹窗
	cancelDialog: boolean
	cancelValue: number
	reason: string
	//操作的会议
	meetingMoid: string
}
type AuditManagerStore = ManagerStore & {
	update: (d: Partial<ManagerStore>) => void
	reset: () => void
	fetchInit: () => void
	auditOpt: (data: { operation: number; audit_by: string; meeting_moid?: string }) => void
}
const initialState: ManagerStore = {
	meetingList: [],
	cancelDialog: false,
	cancelValue: 1,
	reason: '',
	meetingMoid: '',
}
const description = [t('会议时间冲突'), t('会议室资源紧张'), t('视频会议资源紧张')]
export const store = createVanilla<AuditManagerStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		fetchInit: async () => {
			const mask = Message.loading(t('正在加载会议列表，请稍候……'))
			// const { meetingList } = get()
			const res = await fetchApprovalConfs()
			mask.hide()
			if (res.success) {
				set({ meetingList: res.list ? res.list : [] })
			} else {
				Alert(t('操作失败！'), () => {
					window.location.href = './meetingList.html'
				})
			}
		},
		auditOpt: ({ operation, audit_by, meeting_moid }) => {
			const { meetingMoid, reason, cancelValue } = get()
			const mask = Message.loading(t('正在审批会议，请稍候……'))
			let data: {
				meeting_moid: string
				operation: number
				audit_by: string
				desc?: string
				desc_type?: number
			} = {
				meeting_moid: meeting_moid ? meeting_moid : meetingMoid,
				operation: operation,
				audit_by: audit_by,
			}
			if (operation === 3) {
				data.desc_type = cancelValue
				if (cancelValue === 0) {
					data.desc = reason
				} else {
					data.desc = description[cancelValue - 1]
				}
			}
			fetchAuditOPT(data).then((res) => {
				mask.hide()
				if (res.success) {
					window.location.reload()
				} else {
					Alert(res.description || t('审批失败'), () => {
						window.location.reload()
					})
				}
			})
		},
	}))
)
export const useStore = create(store)
